<?php

class MemberExtController extends Uuch_BaseController {

    public function init() {
        parent::init();
        $this->checkLogin();
        $this->setGaCustomVar(4, 'Member', 'true', Uuch_CustomVar::LEVEL_visitor);
    }

    public function rechargeAction() {
        $this->setTitle('我的人民币账户');
        $this->appendCss('/css/home/rmb.css');
        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');
        $this->view->account = $this->currentUser()->getAccount();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $userId = $this->currentUser()->Id;
            $money = $request->getParam('money');
            $recharge = new Application_Model_RechargeBill();
            $recharge->Money = $money;
            $recharge->UserId = $userId;
            $recharge->DateCreated = date('Y-m-d H:i:s');
            $recharge->Name = '充值';
            $recharge->Status = Application_Model_PayBill::PAY_STATUS_CREATED;
            $recharge->save();
            $countItem = Application_Model_RechargeBill::getCountByUserId($userId);
            if ($countItem == 1) {
                $accountItem = Application_Model_UserAccount::addAccount($userId);
                $accountItem->TaskExchangeScore(Application_Model_Task::TASK_RECHARGE);
            }
            $this->_helper->redirector('paying', 'pay', NULL, array('type' => 1, 'id' => $recharge->Id, 'count' => 1));
        }
    }

    public function mailAction() {
        $this->setTitle('我的信箱 | 我的账户');
        $this->appendCss('/css/home/message.css');
        $type = $this->getRequest()->getParam('type', NULL);
        $this->view->type = $type;
        $this->view->mails = Application_Model_Mail::getMail($type, $this->currentUser()->Id, $this->getStart(), $this->pageSize);
    }

    public function openmailAction() {

        $mail = new Application_Model_Mail($this->getRequest()->getParam('postid'));
        $mail->Status = Application_Model_Mail::READED;
        $mail->save();
        $this->json(TRUE);
    }

    public function accounthistoryAction() {

        $this->view->history = $this->currentUser()->getAccount()
                ->getHistory(1, date('Y-m-d', strtotime('-3 months')), date('Y-m-d', strtotime('+1 days')));
    }

    /**
     * 我的个人资料
     */
    public function profileAction() {
        $user_item = $this->currentUser();
        $this->setTitle('个人资料设置');

        $this->view->User = $user_item;
        $this->appendCss('/css/home/personal.css');
        $this->appendScript('/js/My97DatePicker/WdatePicker.js');
        $request = $this->getRequest();
        $profile = $this->currentUser()->Profile;

        if ($profile == NULL) {
            $profile = new Application_Model_Profile();
        }

        if ($request->isPost()) {
            //判断是否有头像数据，有则更新User对象，无则直接跳过，操作Profile对象。
            if ($_FILES["file"]['name'] != '') {
                if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 100000)) {
                    if ($_FILES["file"]["error"] > 0) {
                        //文件上传错误
                    } else {
                        //存放于临时目录中的头像文件名
                        $temp_file_name = $_FILES["file"]["name"];

                        //默认为png格式
                        $file_type = 'png';

                        //获取上传头像的格式后缀名
                        $file_type = end(explode(".", $temp_file_name));

                        //临时用户ID，用于左边填充0，补足9位。
                        $temp_id = $profile->UserId;
                        $temp_id = sprintf("%09d", $temp_id);

                        //1级目录
                        $l1 = substr($temp_id, 0, 3);

                        //2级目录
                        $l2 = substr($temp_id, 3, 2);

                        //3级目录
                        $l3 = substr($temp_id, 5, 2);

                        //文件名
                        $file_name = substr($temp_id, 7) . "." . $file_type;


                        $dir = "data/avatar/$l1/$l2/$l3/";
                        $create_file = Uuch_Util::create_folders($dir);


                        //存放文件到data/avatar目录中
                        move_uploaded_file($_FILES["file"]["tmp_name"], $dir . $file_name);
                        if ($user_item->Pic == null || $user_item->Pic == "") {
                            $accountItem = Application_Model_UserAccount::addAccount($user_item->Id);
                            $accountItem->TaskExchangeScore(Application_Model_Task::TASK_PIC);
                        }
                        //给User对象头像赋值
                        $user_item->Pic = $file_name;

                        $user_item->save();
                    }
                } else {
                    //文件格式错误
                }
            }
            if (($profile->NickName == null || $profile->NickName == "") && $request->getParam('nickName') != "") {
                $accountItem = Application_Model_UserAccount::addAccount($user_item->Id);
                $accountItem->TaskExchangeScore(Application_Model_Task::TASK_USERINFO);
            }
            $profile->NickName = $request->getParam('nickName');
            $profile->Home = $request->getParam('home');
            $profile->Name = $request->getParam('name');
            $profile->Address = $request->getParam('address');
            $profile->Lang = $request->getParam('lang');
            $profile->Birthday = $request->getParam('birthday');
            $profile->Sex = $request->getParam('sex');
            $profile->Description = $request->getParam('description');
            $profile->Email = $request->getParam('email');
            $profile->Qq = $request->getParam('qq');
            $profile->Tel = $request->getParam('tel');
            $profile->UserId = $this->currentUser()->Id;
            $profile->save();
//                        var_dump($user_item);exit;
            $user_item->Nikename = $request->getParam('nickName');
            $user_item->save();
        }

        $this->view->profile = $profile;
    }

    /**
     *  我的RMB帐户
     */
    public function accountAction() {
        $this->setTitle('我的RMB账户 | 我的帐户');
        $this->appendCss('/css/home/rmb.css');
        $start = $this->_getParam('start');
        $this->view->account = $this->currentUser()->Account;
        $this->view->history = $this->view->account->getMoneyChange(date('Y-m-d', strtotime('-1 years')), date('Y-m-d', strtotime('+1 days')), 10, $start);
    }

    /**
     * 我的积分
     */
    public function scoreAction() {
        $this->view->account = $this->currentUser()->Account;
        $start = date('Y-m-d', strtotime('-3 months'));
        $end = date('Y-m-d', strtotime('+1 days'));
        $request = $this->getRequest();
        if ($request->getParam('start')) {
            $start = $request->getParam('start');
        }
        if ($request->getParam('end')) {
            $end = $request->getParam('end');
        }

        $this->view->history = $this->currentUser()->getAccount()->getHistory(2, $start, $end);
    }

    /**
     * 会员中心首页
     */
    public function homeAction() {
        $this->setTitle('我的帐户');
        $this->appendCss('/css/home/home.css');
        $user = $this->currentUser()->Id;
        $this->view->user = $this->currentUser();
        $this->view->mailCount = Application_Model_Mail::getUnRead($user);
        $this->view->inOrder = Application_Model_Order::getCountByStatus($user, Application_Model_Order::STATUS_SELLER_SENDED);
        $this->view->report = 0; //TODO: 补充入库
        $this->view->payOrder = Application_Model_Order::getCountByStatus($user, Application_Model_Order::STATUS_PAYING);
        $this->view->payWaybill = Application_Model_wayBillItem::getItemCount($user, 0);
        $this->view->unSend = Application_Model_Order::getCountByStatus($user, Application_Model_Order::STATUS_UNSEND);
        $this->view->storeAddress = Application_Model_Config::getStoreAddress()->Value;
    }

    /**
     * 我的订单
     */
    public function myorderAction() {
        $this->setTitle('我的代购订单 | 我的帐户');
        $this->appendCss('/css/home/trade.css');
        $this->appendCss('/js/boxy/css/boxy.css');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css'); // 
        $this->appendCss('/admins/css/yundan.css');
        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/boxy/js/jquery.boxy.js');
        $start = $this->_getParam('start');
        if (!$start) {
            $start = 0;
        }

        $status = $this->_getParam('status');
        $keyword = $this->_getParam('keyword');

        $stime = $this->getSafeParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->getSafeParam('etime');
        if (!$etime)
            $etime = 1;

        $startTime = date('Y-m-d', strtotime("$stime months"));
        $endTime = date('Y-m-d', strtotime("$etime months"));

        $this->view->payStatus = Application_Model_Order::getCountByStatus($this->currentUser()->Id, Application_Model_Order::STATUS_PAYING);
        $this->view->sendStatus = Application_Model_Order::getCountByStatus($this->currentUser()->Id, Application_Model_Order::STATUS_SELLER_SENDED);
        $this->view->compStatus = Application_Model_Order::getCountByStatus($this->currentUser()->Id, Application_Model_Order::STATUS_COMPLATED);

        $orderFilter = new Application_Model_Filter_OrderSearch();
        $orderFilter->userid = $this->currentUser()->Id;
        $orderFilter->starttime = $startTime;
        $orderFilter->endtime = $endTime;

        $this->view->orders = Application_Model_Order::getByPages($orderFilter, $this->pageSize, $start);
        $this->view->stime = $stime;
        $this->view->etime = $etime;
        $this->view->orderList = $this->view->orders['list'];
    }
    
    public function orderdetailAction()
    {
        $this->setTitle("代购详情");
        $this->appendCss('/css/home/trade.css');
        $this->appendCss('/js/boxy/css/boxy.css');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css'); // 
        $this->appendCss('/admins/css/yundan.css');
        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/boxy/js/jquery.boxy.js');
        $id = $this->getSafeParam('id');
        if(!$id){
            $this->redirect('myorder', 'member');
            return;
        }
        $result = Application_Model_Order::load($id);
        if ($result->UserId != $this->currentUser()->Id) {
            $this->redirect('myorder', 'member');
            return;
        }
        $this->view->order = $result;
        $this->view->tracklog = Application_Model_Tracking::byUserBlockGetAllByObjectTypeId(Application_Model_DomainobjectType::ObjectType_Order, $id);
    }
    
    /**
     * 获取物流跟踪信息
     */
    public function getingexpressAction() {
        $id = $this->getSafeParam('id');
        $order = Application_Model_Order::load($id);
        $name = $order->Emmis->Name;
        $no = $order->logisticsNo;
        $cemskind = mb_convert_encoding(urldecode($name), 'GB2312', 'UTF-8');
        $cemskind = urlencode($cemskind);
        $niuMen = new Uuch_Express_NiuMen($cemskind, $no);
        $content = $niuMen->getTrackData();
        $this->json(array('content' => $content));
    }

    public function ordercancelAction() {
        $id = $this->_getParam('order');
        $order = Application_Model_Order::load($id);
        if ($order->UserId == $this->currentUser()->Id) {
            if ($order->Status == Application_Model_Order::STATUS_PAYING) {
                $order->Status = Application_Model_Order::STATUS_CANCEL;
                $order->save();
            } else if ($order->Status == Application_Model_Order::STATUS_PAID) {
                $order->Status = Application_Model_Order::STATUS_CANCEL;
                $order->save();
                $account = $this->currentUser()->Account;
                $account->changeMoney($order->getMoney(), Application_Model_UserAccountHistory::TYPE_RECHARGE_MONEY, '取消代购订单' . $order->getBillNo());
            }
        }
        $this->redirect('myorder', 'member');
    }

    /**
     * 更改帐号密码
     * @author wuzw
     */
    public function passwordAction() {
        $user_item = $this->currentUser();
        $this->view->User = $user_item;

        $ret['ret'] = 0;

        $this->appendCss('/css/home/personal.css');
        $this->appendScript('/js/My97DatePicker/WdatePicker.js');
        $request = $this->getRequest();

        if ($request->isPost()) {
            $old_password = $request->getParam('old_password');

            $password = $request->getParam('password');
            $password2 = $request->getParam('password2');

            $old_password_md5 = $user_item->generatePassword($old_password, $user_item->passwordsalt);

            if (strcmp($old_password_md5, $user_item->password) != 0) {
                //旧密码不对
                $ret['ret'] = -1;

                echo json_encode($ret);
                exit;
            } else {
                $user_item->password = $user_item->generatePassword($password, $user_item->passwordsalt);

                $user_item->save();

                $ret['ret'] = 1;

                echo json_encode($ret);
                exit;
            }
        }
    }

    public function passwordsuccessAction() {
        $this->appendCss('/css/home/home.css');
        $this->appendScript('/js/My97DatePicker/WdatePicker.js');

        $user_item = $this->currentUser();
        $this->view->User = $user_item;
    }

    /**
     * 代充值
     */
    public function chargeAction() {

        $this->setTitle('代充值服务');
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/replacerecharge.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $currentUser = $this->currentUser();
        $this->view->user = $currentUser;

        //获取用户状态为1（交易中）的记录数
        $this->view->chargeCount = $currentUser->Account->getTopUpAlipayCount($currentUser->Id, 1);
        $lastCharge = $currentUser->Account->getUserLastTopUpAlipay($currentUser->Id);
        $this->view->lastCharge = isset($lastCharge['list'][0]) ? $lastCharge['list'][0] : "";
        $request = $this->getRequest();
        if ($request->isPost()) {
//			$account = $request->getParam('account');
//			$account_name = $request->getParam('account_name');
//			$money = $request->getParam('money');
//			 
//
//                        //2、通过业务类Application_Model_topUpAlipay插入一条记录
//                        $topUpAlipay = new Application_Model_topUpAlipay();
//
//                        $topUpAlipay->Amount = $money;
//
//                        $topUpAlipay->DateCreated = date('Y-m-d H:i:s',time());
//
//                        $topUpAlipay->ServiceFee = $money*0.05;
//
//                        //1为未处理状态
//                        $topUpAlipay->Status = Application_Model_PayBill::PAY_STATUS_CREATED;
//
//                        $topUpAlipay->UserId = $currentUser->Id;
//
//                        $topUpAlipay->Realname = $account_name;
//
//                        $topUpAlipay->useraccount = $account;
//
//                        $topUpAlipay->save();
//
//                        $this->redirect('paying', 'pay', array('type'=>  Application_Model_PayBill::TYPE_AGENT_RECHANGE,'id'=>$topUpAlipay->Id,'count'=>1));
            $this->redirect("home", "member");
        }
    }

    /**
     * 代充值列表
     */
    public function listAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/replacerecharge.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('我的代充值记录');
        $currentUser = $this->currentUser();
        $this->view->user = $currentUser;

        //获取用户状态为1（交易中）的记录数
        $this->view->chargeCount = $currentUser->Account->getTopUpAlipayCount($currentUser->Id, 1);

        //获取用户所有交易列表
        $this->view->list = $currentUser->Account->getTopUpAlipay($currentUser->Id, 10, 0);
    }

    public function getdwcouponAction() {
        $recharges = Application_Model_RechargeBill::getByUserId($this->currentUser()->Id, Application_Model_PayBill::PAY_STATUS_SUCCESS, '2013-06-01 12:00');
        $ch = Application_Model_CampaignHistory::getByCampaignAndUserId(2, $this->currentUser()->Id);

        $notGetCoupon = Uuch_Util::where($recharges, function($recharge)use($ch) {
                    $has = FALSE;
                    foreach ($ch as $his) {
                        if ($his->description == $recharge->Id) {
                            $has = TRUE;
                        }
                    }
                    return $recharge->Money >= 1000 && !$has;
                });

        if (count($notGetCoupon) == 0) {
            $this->json(array('Value' => -1, 'message' => '对不起,您没有可用的充值领取代金券了!'));
            return;
        }

        $discount = 0;
        if ($notGetCoupon[0]->Money >= 5000) {
            $discount = 500;
        } else if ($notGetCoupon[0]->Money >= 3000) {
            $discount = 240;
        } else if ($notGetCoupon[0]->Money >= 2000) {
            $discount = 120;
        } else if ($notGetCoupon[0]->Money >= 1000) {
            $discount = 50;
        }

        $item = new Application_Model_CampaignHistory();
        $item->UserId = $this->currentUser()->Id;
        $item->CampaignId = Application_Model_CampaignHistory::DWCOUPON;
        $item->DateCreated = date('Y-m-d H:i:s');
        $item->Description = $notGetCoupon[0]->Id;
        $item->save();

        $ah = new Application_Model_AwardHistory();
        $ah->UserName = $this->currentUser()->nikename;
        $ah->AwardName = $discount . '元代金券';
        $ah->AddTime = date('Y-m-d H:i:s');
        $ah->save();


        $batch = Application_Model_CouponBatch::getByNo('DWCoupon');
        $coupon = $batch->createCoupon();
        $coupon->Discount = $discount;
        $coupon->Name .= $discount . '元';
        $coupon->UserId = $this->currentUser()->Id;
        $coupon->save();

        $this->json(array('Value' => 1, 'coupon' => $discount));
    }

    public function recommendAction() {
        $this->setTitle('我的推荐 | 推荐返利历史');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css');
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/clip/zeroclipboard.js');
        $userId = $this->currentUser()->Id;
        $start = $this->getSafeParam('start');
        $adLinkItem = Application_Model_AdLink::getByCode("join");
        $this->view->recommendUrl = $adLinkItem->getAdUrl($userId);

        $rewardItem = Application_Model_Reward::getFiltel(null, $userId, 20, $start);
        $this->view->rewardList = $rewardItem["list"];
        $this->view->rewardAll = $rewardItem;
    }

    public function receiverebateAction() {
        $id = $this->getSafeParam("id");
        $userId = $this->currentUser()->Id;
        $result = Application_Model_Reward::Receive($id, $userId);
        $this->json($result);
    }

}
